package com.example.cardgame

import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.children
import android.widget.Button
import android.widget.GridLayout
import android.widget.TextView
import com.example.cardgame.model.CardMatchingGame

class ThirdActivity : AppCompatActivity(), View.OnClickListener {
    lateinit var game: CardMatchingGame
    val cardButtons = mutableListOf<Button>()
    lateinit var gridLayout: GridLayout
    lateinit var resetButton: Button
    lateinit var scoreTextView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_first)

        gridLayout = findViewById(R.id.gridLayout)
        resetButton = findViewById(R.id.reset)
        scoreTextView = findViewById(R.id.score)

        for (v in gridLayout.children) {
            if (v is Button) {
                v.setOnClickListener(this)
                cardButtons.add(v)
            }
        }
        game = CardMatchingGame(cardButtons.count())
        updateUI()

        resetButton.setOnClickListener {
            game = CardMatchingGame(cardButtons.count())
            updateUI()
        }
    }

    fun updateUI() {
        for (button in cardButtons) {
            val index = cardButtons.indexOf(button)
            val card = game.cardAtIndex(index)
            button.isEnabled = !card.isMatched
            if (card.isChosen) {
                button.text = card.toString()
                button.setBackgroundColor(Color.WHITE)
            } else {
                button.text = ""
                button.setBackgroundResource(R.drawable.img)
            }
        }
        scoreTextView.text = String.format("%s%d", "Score:", game.score)
    }

    override fun onClick(v: View?) {
        if (v is Button) {
            val index = cardButtons.indexOf(v)
            game.chooseCardAtIndex(index)
            updateUI()
        }
    }
}